<template>
  <view class="container">
    <button @click="connectBluetooth">连接蓝牙</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      uuid: "44F4A7D6-A5EA-6B56-61C1-7D092826874E", // 静态 UUID
      bluetoothName: "CXR202407250541", // 静态蓝牙名
    };
  },
  methods: {
    // 连接蓝牙
    connectBluetooth() {
      uni.showLoading({
        title: "正在连接蓝牙...",
        mask: true,
      });

      this.connectBluetoothDevice(this.uuid, this.bluetoothName)
        .then(() => {
          uni.hideLoading();
          uni.showModal({
            title: "提示",
            content: "蓝牙连接成功！",
            showCancel: false,
          });
		  uni.navigateTo({
		  	url: '/waterElectric/chargeWater/chargeWater'
		  })
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showModal({
            title: "提示",
            content: `蓝牙连接失败：${err.message}`,
            showCancel: false,
          });
        });
    },

    // 连接蓝牙设备
    connectBluetoothDevice(uuid, bluetoothName) {
      return new Promise((resolve, reject) => {
        // 初始化蓝牙适配器
        uni.openBluetoothAdapter({
          success: () => {
            console.log("蓝牙适配器初始化成功");

            // 判断设备类型
            if (uni.getSystemInfoSync().platform === "ios") {
              console.log("iOS 设备，通过蓝牙名查找 UUID");
              this.getBluetoothDeviceIdByName(bluetoothName)
                .then((deviceId) => {
                  console.log("找到设备ID:", deviceId);
                  this.createBLEConnection(deviceId)
                    .then(() => resolve())
                    .catch((err) => reject(err));
                })
                .catch((error) => {
                  console.error("错误:", error.message);
                  reject(error);
                });
            } else {
              console.log("Android 设备，直接使用 UUID 连接");
              this.createBLEConnection(uuid)
                .then(() => resolve())
                .catch((err) => reject(err));
            }
          },
          fail: (err) => {
            console.error("蓝牙适配器初始化失败", err);
            reject(new Error("蓝牙适配器初始化失败"));
          },
        });
      });
    },

    // 创建蓝牙连接
    createBLEConnection(deviceId) {
      return new Promise((resolve, reject) => {
        uni.createBLEConnection({
          deviceId,
          success: () => {
            console.log("蓝牙连接成功");
            resolve();
          },
          fail: (err) => {
            console.error("蓝牙连接失败", err);
            reject(new Error("蓝牙连接失败"));
          },
        });
      });
    },

    // 通过蓝牙名获取设备 UUID
    getBluetoothDeviceIdByName(deviceName) {
      return new Promise((resolve, reject) => {
        // 开始蓝牙设备扫描
        uni.startBluetoothDevicesDiscovery({
          success: () => {
            // 获取蓝牙设备列表
            const getDevices = () => {
              uni.getBluetoothDevices({
                success: (res) => {
                  // 遍历设备列表，寻找名称匹配的设备
                  for (let i = 0; i < res.devices.length; i++) {
                    if (res.devices[i].name === deviceName) {
                      // 找到设备，停止扫描并返回设备ID
                      uni.stopBluetoothDevicesDiscovery();
                      resolve(res.devices[i].deviceId);
                      return;
                    }
                  }
                  // 如果未找到设备，继续扫描
                  setTimeout(getDevices, 1000);
                },
                fail: (err) => {
                  // 获取设备列表失败，返回错误信息
                  uni.stopBluetoothDevicesDiscovery();
                  reject(new Error("获取蓝牙设备列表失败：" + err.errMsg));
                },
              });
            };
            // 开始第一次获取设备
            getDevices();
          },
          fail: (err) => {
            // 启动设备扫描失败
            reject(new Error("启动蓝牙设备扫描失败：" + err.errMsg));
          },
        });
      });
    },
  },
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

button {
  padding: 20px 40px;
  font-size: 16px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
}
</style>